<template>
  <el-form
    :model="params"
    :rules="rules"
    ref="form"
    label-width="80px"
    class="register-form-panel"
    @keyup.enter.native="submitForm"
  >
    <el-form-item label-width="0px">
      <h4>用户注册</h4>
    </el-form-item>
    <el-form-item label="手机号码" prop="phoneNumber">
      <el-input v-model="params.phoneNumber" placeholder="请输入手机号码" size="large"></el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="verifyCode">
      <el-input v-model="params.verifyCode" placeholder="请输入验证码" size="large">
        <el-button
          slot="append"
          @click="getCode"
          :disabled="codeBtnDisabled"
          :loading="codeBtnLoading"
        >
          {{ codeBtnText }}
        </el-button>
      </el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        :type="showPassword ? 'text' : 'password'"
        v-model="params.password"
        placeholder="请输入密码"
        size="large"
        auto-complete="off"
      >
        <span slot="suffix" class="el-input-icon" @click="showPassword = !showPassword">
          <i class="fa fa-fw" :class="[showPassword ? 'fa-eye text-primary' : 'fa-eye-slash']"></i>
        </span>
      </el-input>
    </el-form-item>
    <el-form-item label="用户类型">
      <el-radio-group v-model="params.isMerchant" @change="getMerchantPosition">
        <el-radio :label="0">个人注册</el-radio>
        <el-radio :label="1">商户注册</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item
      v-if="params.isMerchant"
      label="商户名称"
      prop="orgName"
      :rules="[{ required: true, message: '请输入商户名称', trigger: 'blur' }]"
    >
      <el-input v-model="params.orgName" placeholder="请输入商户名称" size="large"></el-input>
    </el-form-item>
    <el-form-item v-if="params.isMerchant" label="QQ号码">
      <el-input v-model="params.qqNumber" placeholder="请输入QQ号码" size="large"></el-input>
    </el-form-item>
    <el-form-item v-if="params.isMerchant" label="微信号">
      <el-input v-model="params.wechatNumber" placeholder="请输入微信号" size="large"></el-input>
    </el-form-item>
    <el-form-item prop="isAgree">
      <el-button
        size="large"
        type="primary"
        class="btn-block"
        @click="submitForm"
        :loading="registerLoading"
      >
        立即注册
      </el-button>
      <el-checkbox-group v-model="params.isAgree">
        <el-checkbox label="agree" name="type">
          我已仔细阅读并接受
          <router-link to="/footer/terms" target="_blank">《服务条款》</router-link>
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
  </el-form>
</template>

<script>
import { cookieWrite, cookieGet, amapLoad } from '@vimi/utils-tool'
import { phoneValidator } from '@/common/plugins/validator'

export default {
  components: {},

  props: {},

  data() {
    return {
      params: {
        phoneNumber: '',
        verifyCode: '',
        password: '',
        isAgree: ['agree'],
        isMerchant: 0,
        orgName: '',
        qqNumber: '',
        wechatNumber: '',
        latitude: '',
        longitude: '',
        addressDetail: '',
        addressCode: '',
      },
      rules: {
        phoneNumber: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: phoneValidator, trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        isAgree: [{ required: true, type: 'array', message: '请同意服务条款', trigger: 'change' }],
      },
      //
      codeBtnDisabled: true,
      codeBtnLoading: false,
      codeBtnText: '获取验证码',
      codeCountTime: 60,
      //
      registerLoading: false,
      showPassword: false,
      isFirstTrigger: true,
    }
  },

  computed: {},

  watch: {},

  created() {},

  mounted() {
    this.initCode()
  },

  methods: {
    // 获取验证码
    getCode() {
      this.$refs.form.validateField('phoneNumber', async msg => {
        if (msg) {
          return
        }

        try {
          this.codeBtnLoading = true
          await this.$http.post(`/auth/user/codes/?phoneNumber=${this.params.phoneNumber}`)
          this.$message.success('验证码获取成功，请稍后查看您的手机短信！')

          let time = new Date().getTime() + this.codeCountTime * 1000
          cookieWrite('verifycode', time, this.codeCountTime * 1000)

          this.initInterval(this.codeCountTime)
        } catch (e) {
          if (e && e.status === 400 && e.data.error === 'operate_too_fast') {
            this.$message.error('操作太频繁，请隔60s后再获取！')
          } else {
            this.$message.error('获取验证码失败，请重新获取！(' + e.status + ')')
          }
        } finally {
          this.codeBtnLoading = false
        }
      })
    },

    // 初始化验证码
    initCode() {
      let verifyCookie = cookieGet('verifycode') || 0
      let time = Math.ceil((+verifyCookie - new Date().getTime()) / 1000)
      if (time > 0) {
        this.initInterval(time)
      } else {
        this.codeBtnDisabled = false
      }
    },

    // 设置验证码倒计时
    initInterval(time) {
      let resend = setInterval(() => {
        time--
        if (time > 0) {
          this.codeBtnText = time + '秒后重新获取'
          this.codeBtnDisabled = true
        } else {
          clearInterval(resend)
          this.codeBtnText = '获取验证码'
          this.codeBtnDisabled = false
        }
      }, 1000)
    },

    // 提交注册
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.postLogin()
        } else {
          this.$message.error('输入错误，请重新输入')
        }
      })
    },

    // 请求注册
    async postLogin() {
      try {
        this.registerLoading = true

        let params = {
          phoneNumber: this.params.phoneNumber,
          verifyCode: this.params.verifyCode,
          password: this.params.password,
          userName: this.params.phoneNumber,
        }

        if (this.params.isMerchant) {
          // 商户
          params.orgName = this.params.orgName
          params.clientOrgClass = 'org_service_provider'
          params.qqNumber = this.params.qqNumber
          params.wechatNumber = this.params.wechatNumber
          params.longitude = this.params.longitude
          params.latitude = this.params.latitude
          params.addressCode = this.params.addressCode
          params.addressDetail = this.params.addressDetail

          await this.$http.post('/auth/org/corp/', params)
          this.$message.success('恭喜，您已注册成为黔农担平台用户！')
        } else {
          // 个人
          params.applyClientId = ['personal']
          params.defaultClientId = 'personal'

          await this.$http.post('/auth/user/', params)
          this.$message.success('恭喜，您已注册成为黔农担平台用户！')
        }
        this.$router.push('/')
      } catch (e) {
        if (
          e &&
          e.status === 400 &&
          e.data &&
          e.data.error === 'invalid_param' &&
          /^invalid\sverify\scode/.test(e.data.errorDescription)
        ) {
          this.$message.error('验证码错误，请重新输入！')
        } else if (e && e.status === 400 && e.data && e.data.error === 'phone_number_is_exists') {
          this.$message.error('手机号码已经存在，请更换手机号码后重新注册！')
        } else {
          this.$message.error('注册失败，请重新注册！')
        }
      } finally {
        this.registerLoading = false
      }
    },

    getMerchantPosition() {
      if (this.isFirstTrigger) {
        amapLoad().then(() => this.getLngLat())
        this.isFirstTrigger = false
      }
    },

    // 获取经纬度
    async getLngLat() {
      if (!window.AMap) {
        return
      }
      const vm = this
      let mapObj = new window.AMap.Map('iCenter')
      mapObj.plugin('AMap.Geolocation', () => {
        let geolocation = new window.AMap.Geolocation()
        mapObj.addControl(geolocation)
        geolocation.getCurrentPosition((status, result) => {
          if (result && result.position) {
            let ac = result.addressComponent
            vm.params.latitude = result.position.lat
            vm.params.longitude = result.position.lng
            vm.params.addressDetail = result.formattedAddress
            vm.params.addressCode = ac ? (ac.adcode || '') + '000000' : ''
          }
        })
      })
    },
  },
}
</script>

<style scoped>
.register-form-panel {
  padding: 20px;
  margin: 0 auto;
  max-width: 450px;
}
</style>
